/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.biz.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.HttpClientUtils;
import com.thinkgem.jeesite.common.utils.excel.ExportExcel;
import com.thinkgem.jeesite.modules.biz.dao.BizGoodsDao;
import com.thinkgem.jeesite.modules.biz.dao.BizOrderdetailDao;
import com.thinkgem.jeesite.modules.biz.entity.BizGoods;
import com.thinkgem.jeesite.modules.biz.entity.BizOrderdetail;
import com.thinkgem.jeesite.modules.biz.form.OrderToCrmForm;
import com.thinkgem.jeesite.modules.biz.service.BizOrderdetailService;
import com.thinkgem.jeesite.modules.sys.utils.DictUtils;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.modules.biz.entity.BizOrder;
import com.thinkgem.jeesite.modules.biz.service.BizOrderService;

import java.io.IOException;
import java.util.*;

/**
 * 订单Controller
 * @author tiancheng
 * @version 2018-09-17
 */
@Controller
@RequestMapping(value = "${adminPath}/biz/bizOrder")
public class BizOrderController extends BaseController {

	@Autowired
	private BizOrderService bizOrderService;
	@Autowired
	private BizOrderdetailService bizOrderdetailService;
	@Autowired
	private BizOrderdetailDao bizOrderdetailDao;
	@Autowired
	private BizGoodsDao bizGoodsDao;

	private static Logger log = LoggerFactory.getLogger(ExportExcel.class);

	@ModelAttribute
	public BizOrder get(@RequestParam(required=false) String id) {
		BizOrder entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = bizOrderService.get(id);
		}
		if (entity == null){
			entity = new BizOrder();
		}
		return entity;
	}
	
	@RequiresPermissions("biz:bizOrder:view")
	@RequestMapping(value = {"list", ""})
	public String list(BizOrder bizOrder, HttpServletRequest request, HttpServletResponse response, Model model) {
		if(bizOrder != null && StringUtils.isEmpty(bizOrder.getIsCanOut()) && null == bizOrder.getNoIsCanOut()){
			bizOrder.setIsCanOut("1");
		}
		Page<BizOrder> page = bizOrderService.findPage(new Page<BizOrder>(request, response), bizOrder); 
		model.addAttribute("page", page);
		return "modules/biz/bizOrderList";
	}

	@RequiresPermissions("biz:bizOrder:view")
	@RequestMapping(value = "form")
	public String form(BizOrder bizOrder, Model model) {
		if(bizOrder != null && StringUtils.isNotEmpty(bizOrder.getId())){
			BizOrderdetail bizOrderdetail = new BizOrderdetail();
			bizOrderdetail.setOutboundOrderPid(bizOrder.getId());
			List<BizOrderdetail> orderDetailList = bizOrderdetailService.findList(bizOrderdetail);
			bizOrder.setBizOrderDetailList(orderDetailList);
			model.addAttribute("orderDetailList", orderDetailList);
		}
		model.addAttribute("bizOrder", bizOrder);
		return "modules/biz/bizOrderForm";
	}

	@RequiresPermissions("biz:bizOrder:edit")
	@RequestMapping(value = "save")
	public String save(BizOrder bizOrder, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, bizOrder)){
			return form(bizOrder, model);
		}
		bizOrderService.save(bizOrder);
		addMessage(redirectAttributes, "保存订单成功");
		return "redirect:"+Global.getAdminPath()+"/biz/bizOrder/?repage";
	}
	
	@RequiresPermissions("biz:bizOrder:edit")
	@RequestMapping(value = "delete")
	public String delete(BizOrder bizOrder, RedirectAttributes redirectAttributes) {
		bizOrderService.delete(bizOrder);
		addMessage(redirectAttributes, "删除订单成功");
		return "redirect:"+Global.getAdminPath()+"/biz/bizOrder/?repage";
	}

	/**
	 * 打印单张
	 * @param bizOrder
	 * @param redirectAttributes
	 * @param model
	 * @return
	 */
	@RequiresPermissions("biz:bizOrder:print")
	@RequestMapping(value = "print")
	public String print(BizOrder bizOrder, RedirectAttributes redirectAttributes, Model model) {
		if(bizOrder != null && StringUtils.isNotEmpty(bizOrder.getId())){
			BizOrder order = bizOrderService.get(bizOrder.getId());
			BizOrderdetail bizOrderdetail = new BizOrderdetail();
			bizOrderdetail.setOutboundOrderPid(bizOrder.getId());
			List<BizOrderdetail> orderDetailList = null;
			orderDetailList = bizOrderdetailService.findList(bizOrderdetail);
			List<List<BizOrderdetail>> orderDetailLists = Lists.partition(orderDetailList, 9);
			List<Object> orderMapList = new ArrayList<>();	//存放订单map对象
			if(orderDetailList != null){
				for (int i = 0; i < orderDetailLists.size(); i++) {
					HashMap<String, Object> orderMap_i = new HashMap<>(16);
					orderMap_i.put("title","销售出库单");	//标题
					orderMap_i.put("businessType",DictUtils.getDictLabel(order.getOrderType(),"biz_order_order_type",""));	//出库类别
					orderMap_i.put("outgoingCategory", DictUtils.getDictLabel(order.getDeliverType(),"sm_outbound_order_deliver_type",""));	//发货方式 deliverType
					orderMap_i.put("warehouse","冠普仓库");	//仓库
					orderMap_i.put("outDate", DateUtils.getDate("yyyy-MM-dd"));	//出库日期
					orderMap_i.put("customer",order.getCustomerName());	//客户
					orderMap_i.put("teamName",order.getTeamName());	//团队/部门
					orderMap_i.put("address",order.getAddress());	//收货地址
					orderMap_i.put("remarks",order.getRemarks());	//备注
					orderMap_i.put("name",order.getName());	//编码
					orderMap_i.put("tmUrl",order.getTmUrl());	//条形码
					orderMap_i.put("createBy",order.getCreateByName());	//创建人
					orderMap_i.put("auditorName",order.getAuditorName());	//审核人
					Date auditDate = order.getAuditDate();
					if(auditDate != null){
						orderMap_i.put("auditDate", DateUtils.formatDate(auditDate,"yyyy-MM-dd"));	//审核日期
					}else{
						orderMap_i.put("auditDate", "");	//审核日期
					}
					List<BizOrderdetail> orderDetails = orderDetailLists.get(i);
					Integer totalQuantity_i = 0;	//总数量
					for (BizOrderdetail orderDetail : orderDetails) {
						if(orderDetail != null){
							totalQuantity_i = totalQuantity_i + orderDetail.getQuantity();
						}
					}
					orderMap_i.put("orderDetails",orderDetails);	//出库明细
					orderMap_i.put("totalQuantity",totalQuantity_i);
					orderMapList.add(orderMap_i);
				}
			}
			model.addAttribute("orderMapList", orderMapList);
			model.addAttribute("count",orderMapList.size());
		}
		return "modules/biz/bizOrderPrints";
	}


	 /**
	  * 批量打印
	  * @author tiancheng
	  * @date 2018/11/2 14:56
	  * @param
	  * @return
	  */
	@RequiresPermissions("biz:bizOrder:prints")
	@RequestMapping(value = "prints")
	public String prints(BizOrder bizOrder, Model model) {
		//存放订单map对象
		List<Object> orderMapList = new ArrayList<>();
		if(bizOrder.getOrderIds().length > 0){
			for (String orderId:bizOrder.getOrderIds()) {
				BizOrder order = bizOrderService.get(orderId);
				BizOrderdetail bizOrderdetail = new BizOrderdetail();
				bizOrderdetail.setOutboundOrderPid(order.getId());
				List<BizOrderdetail> orderDetailList = null;
				orderDetailList = bizOrderdetailService.findList(bizOrderdetail);
				List<List<BizOrderdetail>> orderDetailLists = Lists.partition(orderDetailList, 9);
				if(orderDetailList != null){
					for (int i = 0; i < orderDetailLists.size(); i++) {
						HashMap<String, Object> orderMap_i = new HashMap<>(16);
						orderMap_i.put("title","出库单");	//标题
						orderMap_i.put("businessType",DictUtils.getDictLabel(order.getOrderType(),"biz_order_order_type",""));	//出库类别
						orderMap_i.put("outgoingCategory", DictUtils.getDictLabel(order.getDeliverType(),"sm_outbound_order_deliver_type",""));	//发货方式 deliverType
						orderMap_i.put("warehouse","冠普仓库");	//仓库
						orderMap_i.put("outDate", DateUtils.getDate("yyyy-MM-dd"));	//出库日期
						orderMap_i.put("customer",order.getCustomerName());	//客户
						orderMap_i.put("teamName",order.getTeamName());	//团队/部门
						orderMap_i.put("address",order.getAddress());	//收货地址
						orderMap_i.put("remarks",order.getRemarks());	//备注
						orderMap_i.put("name",order.getName());	//编码
						orderMap_i.put("tmUrl",order.getTmUrl());	//条形码
						orderMap_i.put("createBy",order.getCreateByName());	//创建人
						orderMap_i.put("auditorName",order.getAuditorName());	//审核人
						Date auditDate = order.getAuditDate();
						if(auditDate != null){
							orderMap_i.put("auditDate", DateUtils.formatDate(auditDate,"yyyy-MM-dd"));	//审核日期
						}else{
							orderMap_i.put("auditDate", "");	//审核日期
						}

						List<BizOrderdetail> orderDetails = orderDetailLists.get(i);
						Integer totalQuantity_i = 0;	//总数量
						for (BizOrderdetail orderDetail : orderDetails) {
							if(orderDetail != null){
								totalQuantity_i = totalQuantity_i + orderDetail.getQuantity();
							}
						}
						orderMap_i.put("orderDetails",orderDetails);	//出库明细
						orderMap_i.put("totalQuantity",totalQuantity_i);
						orderMapList.add(orderMap_i);
					}
				}
				model.addAttribute("orderMapList", orderMapList);
				model.addAttribute("count",orderMapList.size());
			}
		}
		return "modules/biz/bizOrderPrints";
	}



	/**
	  * 出库单的二次出库时的校验
	  * @author tiancheng  
	  * @date 2018/10/7 9:20
	  * @param
	  * @return   
	  */
	@ResponseBody
	@RequestMapping(value = "secondary")
	public String secondary(BizOrder bizOrder, RedirectAttributes redirectAttributes) {
		String msg = "";
		//查询该订单下的未出库的明细
		BizOrderdetail bizOrderdetail = new BizOrderdetail();
		bizOrderdetail.setOutboundOrderPid(bizOrder.getId());
		bizOrderdetail.setIsDeliver("1");
		List<BizOrderdetail> bizOrderdetailList = bizOrderdetailDao.findList(bizOrderdetail);
		//定义开关
		boolean a = true;
		StringBuffer yes = new StringBuffer();
		StringBuffer no = new StringBuffer();
		if(null == bizOrderdetailList || bizOrderdetailList.size() == 0){
			msg = "当前出库单下面没有未出库的商品！";
		}else{
			for (BizOrderdetail orderdetail:bizOrderdetailList) {
				//查询商品的库存是否满足当前的待出库的数量
				BizGoods bizGoods = bizGoodsDao.getByGoodsCode(orderdetail.getCode());
				if(bizGoods.getSureStockAmount() >= orderdetail.getQuantity()){
					//可以出库的商品
					yes.append(bizGoods.getGoodsName()+",");
				}else{
					a = false;
					//不可以出库的商品
					no.append(bizGoods.getGoodsName()+",");
				}
			}
			if(a){
				msg = "校验成功，该订单可正常出库！已将该出库单修改为可出库状态";
				//修改商品可用库存,将该出库单设置为可出库
				for (BizOrderdetail orderdetail : bizOrderdetailList) {
					BizGoods bizGoods = bizGoodsDao.getByGoodsCode(orderdetail.getCode());
					if(bizGoods.getSureStockAmount() >= orderdetail.getQuantity()){
						//修改可用库存和商品明细的数量
						Integer sureStockAmount = bizGoods.getSureStockAmount() - orderdetail.getQuantity();
						bizGoods.setSureStockAmount(sureStockAmount);
						bizGoods.setWaitStockAmount(orderdetail.getQuantity());
						bizGoodsDao.updateInfo(bizGoods);

						orderdetail.setIsDeliver("0");
						bizOrderdetailDao.update(orderdetail);
					}
				}
				bizOrder.setIsCanOut("1");
				bizOrderService.update(bizOrder);
			}else{
				String dataYes = "";
				String dataNo = "";
				StringBuffer stringBuffer = new StringBuffer();
				if(yes.length() > 0){
					dataYes = yes.substring(0,no.length() - 1);
					stringBuffer.append("商品明细中【"+dataYes+"】已经可以出库 ");
				}
				if(no.length() > 0){
					dataNo = no.substring(0,no.length() - 1);
					stringBuffer.append("【"+dataNo+"】商品数量不足！该出库单不可出库");
				}
				msg = stringBuffer.toString();
			}
		}
		return msg;

	}



	 /**
	  * 订单作废并同步CRM
	  * @author tiancheng
	  * @date 2018/11/13 14:36
	  * @param2
	  * @return
	  */  
//	@RequiresPermissions("biz:bizOrder:discarded")
//	@RequestMapping(value = "discarded")
//	public String discarded(BizOrder bizOrder, RedirectAttributes redirectAttributes) {
//		if(bizOrder != null && StringUtils.isNotEmpty(bizOrder.getId())){
//			String bizOrderId2 = "";
//			String bizOrderId = bizOrder.getId();
//			String lastOne = bizOrderId.substring(bizOrderId.length()-1,bizOrderId.length());
//			if("F".equals(lastOne)){
//				//点击不1出库单的作废按钮
//				bizOrderId2 = bizOrderId.substring(0,bizOrderId.length()-1);
//				//同步CRM
//				OrderToCrmForm orderToCrmForm = new OrderToCrmForm();
//				orderToCrmForm.setOrderId(bizOrderId2);
//				orderToCrmForm.setContent(bizOrder.getContent());
//				orderToCrmForm.setOperationId(UserUtils.getUser().getId());
//				orderToCrmForm.setOperationName(UserUtils.getUser().getName());
//				String jsonString = JSON.toJSONString(orderToCrmForm);
//				try {
//					String path = Global.getConfig("crm.interface.path");
//					HttpClientUtils.sendPost(jsonString,path+"/a/api/smOutboundOrder/update","");
//				} catch (IOException e) {
//					e.printStackTrace();
//				}
//				log.warn("id为"+bizOrderId2+"的订单被--"+ UserUtils.getUser().getName()+"废弃");
//			}else{
//				//点击可出库单的作废按钮
//				bizOrderId2 = bizOrderId + "F";
//				//同步CRM
//				OrderToCrmForm orderToCrmForm = new OrderToCrmForm();
//				orderToCrmForm.setOrderId(bizOrderId);
//				orderToCrmForm.setContent(bizOrder.getContent());
//				orderToCrmForm.setOperationId(UserUtils.getUser().getId());
//				orderToCrmForm.setOperationName(UserUtils.getUser().getName());
//				String jsonString = JSON.toJSONString(orderToCrmForm);
//				try {
//					String path = Global.getConfig("crm.interface.path");
//					HttpClientUtils.sendPost(jsonString,path+"/a/api/smOutboundOrder/update","");
//				} catch (IOException e) {
//					e.printStackTrace();
//				}
//				log.warn("id为"+bizOrderId+"的订单被--"+ UserUtils.getUser().getName()+"废弃");
//			}
//			BizOrder bizOrder2 = bizOrderService.get(bizOrderId2);
//			if(bizOrder2 != null && StringUtils.isNotEmpty(bizOrder2.getId())){
//				//作废订单
//				bizOrderService.discarded(bizOrder2);
//			}
//			//作废订单
//			bizOrderService.discarded(bizOrder);
//		}
//		addMessage(redirectAttributes, "作废成功，商品库存已经刷新！");
//		return "redirect:"+Global.getAdminPath()+"/biz/bizOrder/?repage";
//	}


	 /**
	  * 领取物料的列表
	  * @author tiancheng
	  * @date 2018/12/4 10:51
	  * @param
	  * @return
	  */
	@RequiresPermissions("biz:bizOrder:receiveListView")
	@RequestMapping(value = "receiveList")
	public String receiveList(BizOrder bizOrder, HttpServletRequest request, HttpServletResponse response, Model model) {
		if(bizOrder != null && StringUtils.isEmpty(bizOrder.getIsCanOut()) && null == bizOrder.getNoIsCanOut()){
			bizOrder.setIsCanOut("1");
		}
		Page<BizOrder> page = bizOrderService.findReceivePage(new Page<BizOrder>(request, response), bizOrder);
		model.addAttribute("page", page);
		return "modules/biz/bizOrderReceiveList";
	}


	/**
	 * 领取物料
	 * @author tiancheng
	 * @date 2018/12/4 11:06
	 * @param
	 * @return
	 */
	@RequiresPermissions("biz:bizOrder:receiveListView")
	@RequestMapping(value = "receiveForm")
	public String receiveForm(BizOrder bizOrder, Model model) {
		if(bizOrder != null && StringUtils.isNotEmpty(bizOrder.getId())){
			BizOrderdetail bizOrderdetail = new BizOrderdetail();
			bizOrderdetail.setOutboundOrderPid(bizOrder.getId());
			List<BizOrderdetail> orderDetailList = bizOrderdetailService.findListReceive(bizOrderdetail);
			bizOrder.setBizOrderDetailList(orderDetailList);
			model.addAttribute("orderDetailList", orderDetailList);
			model.addAttribute("goodsNum", orderDetailList.size());
		}
		model.addAttribute("bizOrder", bizOrder);
		model.addAttribute("bizGoods", new BizGoods());
		return "modules/biz/bizOrderReceiveForm";
	}


	 /**
	  * 领取物料的保存
	  * @author tiancheng  
	  * @date 2018/12/4 13:59
	  * @param
	  * @return   
	  */  
	@RequiresPermissions("biz:bizOrder:receiveListSave")
	@RequestMapping(value = "receiveSave")
	public String receiveSave(BizOrder bizOrder) {
		bizOrderdetailService.receiveSave(bizOrder);
		return "redirect:"+Global.getAdminPath()+"/biz/bizOrder/receiveList";
	}


	 /**
	  * 物料领取的审核
	  * @author tiancheng  
	  * @date 2018/12/4 15:16
	  * @param
	  * @return   
	  */  
	@RequestMapping(value = "updateTaskState")
	public String updateTaskState(BizOrder bizOrder, RedirectAttributes redirectAttributes) {
		//审核通过修改 状态
		if(bizOrder.getTaskState().equals("2")){
			bizOrder.setDelFlag("0");
			bizOrder.setOrderApprovalStatus("20");
		}
		bizOrderService.save(bizOrder);
		addMessage(redirectAttributes, "审核成功！");
		return "redirect:"+Global.getAdminPath()+"/biz/bizOrder/receiveList";
	}
	
	/**
	 * 领取物料
	 * @author tiancheng
	 * @date 2018/12/4 11:06
	 * @param
	 * @return
	 */
	@RequestMapping(value = "treeData")
	public List<Map<String,Object>> treeData(BizGoods bizGoods) {
		return bizGoodsDao.findListMap(bizGoods);
	}
}